from PySide6.QtWidgets import QApplication, QFileDialog, QMessageBox
from PySide6.QtCore import QDir
import sys
import os


class FolderSelector:
    """
    PySide6 文件夹选择器
    """

    def __init__(self):
        self.app = None

    def select_folder(self, title="选择文件夹", initial_dir=None):
        """
        选择文件夹

        Args:
            title: 对话框标题
            initial_dir: 初始目录，默认为当前工作目录

        Returns:
            str: 选择的文件夹路径，如果取消则为空字符串
        """
        # 如果没有现有的 QApplication 实例，则创建一个
        if not QApplication.instance():
            self.app = QApplication(sys.argv)
        else:
            self.app = QApplication.instance()

        # 设置初始目录
        if initial_dir is None:
            initial_dir = os.getcwd()
        elif not os.path.exists(initial_dir):
            initial_dir = os.getcwd()

        # 选择文件夹
        folder_path = QFileDialog.getExistingDirectory(
            None,
            title,
            initial_dir,
            QFileDialog.Option.ShowDirsOnly | QFileDialog.Option.DontResolveSymlinks
        )

        return folder_path

    def select_folder_with_validation(self, title="选择文件夹", must_exist=True):
        """
        选择文件夹并进行验证

        Args:
            title: 对话框标题
            must_exist: 是否必须存在

        Returns:
            str: 验证通过的文件夹路径，或空字符串
        """
        folder_path = self.select_folder(title)

        if folder_path and must_exist:
            if not os.path.exists(folder_path):
                self.show_message("错误", f"文件夹不存在: {folder_path}")
                return ""
            if not os.path.isdir(folder_path):
                self.show_message("错误", f"路径不是文件夹: {folder_path}")
                return ""

        return folder_path

    def show_message(self, title, message):
        """显示消息对话框"""
        msg_box = QMessageBox()
        msg_box.setWindowTitle(title)
        msg_box.setText(message)
        msg_box.exec()


# 使用示例
if __name__ == "__main__":
    selector = FolderSelector()

    # 基本用法
    selected_folder = selector.select_folder("请选择目标文件夹")
    if selected_folder:
        print(f"选择的文件夹: {selected_folder}")
        print(f"绝对路径: {os.path.abspath(selected_folder)}")
    else:
        print("未选择文件夹")

    # 带验证的用法
    valid_folder = selector.select_folder_with_validation(
        "请选择存在的文件夹",
        must_exist=True
    )
    if valid_folder:
        print(f"验证通过的文件夹: {valid_folder}")